package cn.qidisoft.edu.hzjt.service.zyc.impl;

import cn.qidisoft.core.common.code.QdfRespCode;
import cn.qidisoft.core.common.exception.dao.DBException;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.StringUtils;
import cn.qidisoft.core.util.moffice.excel.ErrorMessageBean;
import cn.qidisoft.core.util.moffice.excel.ExcelUtil;
import cn.qidisoft.core.util.moffice.excel.ImportMsgHelper;
import cn.qidisoft.edu.hzjt.dao.zyc.DfMapper;
import cn.qidisoft.edu.hzjt.model.zyc.PartyMembershipDues;
import cn.qidisoft.edu.hzjt.service.zyc.IDfService;
import cn.qidisoft.edu.hzjt.utils.LogType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.ibatis.session.RowBounds;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;

/**
 * 党费业务层实现类
 * @author zhangwenliang
 *@Date 2018.11.21
 */

@Service
public class DfServiceImpl implements IDfService{
	protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);
	@Autowired
	private DfMapper dfMapper;
	
	@Override
	public PaginationBean<PartyMembershipDues> getListData(Map<String, Object> queryMap, Page page) {
		int c = dfMapper.getCounnt(queryMap);
		int totalRecords = 0;
		totalRecords = (int) c;
		PaginationBean<PartyMembershipDues> pageHolder = new PaginationBean<PartyMembershipDues>(page, totalRecords);
		List<PartyMembershipDues> resultList = dfMapper.getListData(queryMap,
				new RowBounds((pageHolder.getCurrentPage() - 1) * pageHolder.getPageSize(), pageHolder.getPageSize()));
		pageHolder.setPageList(resultList);
		return pageHolder;
	}
	
	@Override
    @Transactional
    public void delete(List<Integer> data) {
        try {
        	dfMapper.delete(data);
        } catch (Exception e) {
            LOGGER.error("delete [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(),
                ToStringBuilder.reflectionToString(data, ToStringStyle.SHORT_PREFIX_STYLE));
            throw new DBException(QdfRespCode.QDF_020002.getCode(), QdfRespCode.QDF_020002.getMsg(),
                e);
        }
    }
	
	@Override
	public List<PartyMembershipDues> getDfList(Map<String, Object> queryMap) {
		return dfMapper.getDfList(queryMap);
	}

	@Override
	public void insertDfInfo(PartyMembershipDues partyMembershipDues) {
		dfMapper.insertDfInfo(partyMembershipDues);
		
	}

	@Override
	public PartyMembershipDues getById(int parseInt) {
		return dfMapper.getById(parseInt);
	}

	@Override
	public int updateDfinfo(PartyMembershipDues pM) {
		
		return dfMapper.updateDfinfo(pM);
	}
	
	
	 /**
	   * 具体导入方法代码按照这个写
	   * 
	   * @see cn.qidisoft.edu.hzjt.service.IStudentDemoService#importStudentDemo(java.util.List,
	   *      org.apache.poi.hssf.usermodel.HSSFWorkbook, org.apache.poi.hssf.usermodel.HSSFSheet,
	   *      java.lang.String[], int, java.io.InputStream, java.lang.Long)
	   */
	@Override
	public List<ErrorMessageBean> importDfInfo(List<ErrorMessageBean> errorList, HSSFWorkbook wb, HSSFSheet sheet,
			String[] header, int totalRows, InputStream in, Integer exportFlag) {
		  try {
			  String[] filedNameArr_info = new String[] {"gID","dYID", "dFNF","dFYF","dFJE","remark","creatorId","creatorName","createTime"};
		      String[] filedChineseNameArr_info = new String[] {"标识id", "党员ID", "党费年份","党费月份","党费金额","备注","添加人的系统用户ID","添加人姓名","添加时间"}; // 中文字段名称
		      int[] fieldMustFlag_info = new int[] {1, 1, 1, 1, 1, 0, 1, 1, 1}; // 是否是必填项
		      // 检查excel表头信息是否有效
		      if (header == null || totalRows <= 1) {
		        ImportMsgHelper.addErrorList(errorList, "sys-error", ImportMsgHelper.msg_validate_0002);
		        return errorList;
		      }
		      boolean isExist = false;
		      List<Integer> realFieldsIndex = new LinkedList<Integer>(); // 找到数据库配置的字段中文描述数组中的下标
		      List<Integer> realFieldsInExcelIndex = new LinkedList<Integer>(); // 找到对应项在EXCEL中的 列位置
		      for (int i = 0; i < filedChineseNameArr_info.length; i++) { // 这个是数据库配置中文字段集合
		        isExist = false;
		        for (int j = 0; j < header.length; j++) { // 这个是EXCEL表头集合
		          if (!header[j].equals("")
		              && filedChineseNameArr_info[i].trim().equals(header[j].toString().trim())) {
		            isExist = true;
		            realFieldsIndex.add(i);
		            realFieldsInExcelIndex.add(j);
		            break;
		          }
		        }
		        if (!isExist) { // 如果在excel第一行 不存在该项导入，更新的字段中文名
		          if (fieldMustFlag_info[i] == 1) {// 必导入列
		            ImportMsgHelper.addErrorList(errorList, "sys-error",
		                "导入的excel文件中找不到" + filedChineseNameArr_info[i] + "项！");
		          }
		        }
		      }
		      boolean isValidate = true; // 判断输入字段是否有效
		      HSSFRow hSSFRow = null;
		      int rowNum = 0; // 获得行Number
		      boolean bool = false;
		      Map<String, String> rowFieldMap = null;
		      Map<String, Integer> rowFieldIndexMap = null;
		      PartyMembershipDues partyMembershipDues = null;
		      String gID = null;   // 标识id(无用)
		      String  dYID = null; // 党员id
			  String  dFNF = null;        // 党费年份
			  String  dFYF = null;       // 党费月份
			  String   dFJE = null;    // 党费金额
			  String  remark= null;    // 备注
			  String  creatorId;     //添加人的系统用户ID
		      String creatorName;    //添加人姓名
		      String createTime;     //添加时间
		      List<PartyMembershipDues> studentList = new ArrayList<PartyMembershipDues>();
		      // 开始对每行数据进行操作
		      for (int row = 1; row < totalRows; row++) {
		        rowFieldIndexMap = null;
		        isValidate = true;
		        rowFieldMap = new HashMap<String, String>();
		        rowFieldIndexMap = new HashMap<String, Integer>();
		        String cellValue = null; // 获得每一个单元个的值
		        hSSFRow = sheet.getRow(row); // 获得一行数据
		        rowNum = row + 1;
		        if (hSSFRow == null) { // 不存在要导入的数据
		          continue;
		        }
		        int j = 0;
		        gID = null;   // 标识id(无用)
			    dYID = null; // 党员id
			    dFNF = null;        // 党费年份
			    dFYF = null;       // 党费月份
			    dFJE = null;    // 党费金额
			    remark= null;    // 备注
			    creatorId = null;     //添加人的系统用户ID
			    creatorName = null;    //添加人姓名
			    createTime = null;     //添加时间
		        bool = false;
		        for (int i = 0; i < realFieldsIndex.size(); i++) {// 读值到map中
		          cellValue = ExcelUtil.getStringByRowAndCol(sheet, row, realFieldsInExcelIndex.get(i));
		          // 获得当前map中当前字段索引值
		          j = realFieldsIndex.get(i);
		          // 验证当前值如果为空，将值设置为空字符
		          if (cellValue == null || cellValue.equals("null")) {
		            cellValue = "";
		          }
		          cellValue = cellValue.trim();
		          // 验证当前值是否是“空”或"",将必填项字段不允许这么填
		          if ("".equals(cellValue) || cellValue.length() == 0) {
		            if (fieldMustFlag_info[j] == 1) {// 最基本验证,过滤到必填项为空记录
		              ImportMsgHelper.addNullValueErrorMessage(errorList, rowNum,
		                  filedChineseNameArr_info[j]);
		              isValidate = false; // 这行数据没有通过初步验证
		              break;
		            }
		          }
		          rowFieldMap.put(filedNameArr_info[j], cellValue); // 存放字段值
		          rowFieldIndexMap.put(filedNameArr_info[j], j); // 存放字段索引
		        }
		        if (isValidate) { // 表示对execl数据校成功，进行数据处理
		        	gID = rowFieldMap.get("gID"); //
		          if (StringUtils.isNullValue(gID) && gID.length() >= 101) {
		            ImportMsgHelper.addErrorList(errorList, "第" + rowNum + "行数据有错",
		                filedChineseNameArr_info[rowFieldIndexMap.get("name")] + "字段不能为空,且输入(1~100)个字符之间！");
		            bool = true;
		            continue;
		          } else {
		            if (exportFlag != null && exportFlag == 2) { // 修改
		              // 从数据库中取数据
		              // 交付数据库，假设返回值是1
		              // int num=studentDemoService.queryStudentByCount();
		              int num = 1;
		              if (num == 1) { // 标识找到
		                // studentDemo =studentDemoService.queryByPk();
		              } else {
		                ImportMsgHelper.addErrorList(errorList, "第" + rowNum + "行数据有错", " 数据不存在，不能做更新操作！");
		                bool = true;
		                continue;
		              }
		            } else { // 代表新增
						partyMembershipDues = new PartyMembershipDues();
						partyMembershipDues.setgID("");
		            }
		          }
					dYID = rowFieldMap.get("dYID");
					dFNF = rowFieldMap.get("dFNF");
					dFYF = rowFieldMap.get("dFYF");
					dFJE = rowFieldMap.get("dFJE");
					remark = rowFieldMap.get("remark");
					creatorId = rowFieldMap.get("creatorId");
					creatorName = rowFieldMap.get("creatorName");
					createTime = rowFieldMap.get("createTime");
                    partyMembershipDues.setdYID(Integer.parseInt(dYID));
                    partyMembershipDues.setdFNF(Integer.parseInt(dFNF));
                    partyMembershipDues.setdFYF(Integer.parseInt(dFYF));
                    partyMembershipDues.setdFJE(Double.parseDouble(dFJE));
                    partyMembershipDues.setRemark(remark);
                    partyMembershipDues.setCreatorId(Integer.parseInt(creatorId));
                    partyMembershipDues.setCreatorName(creatorName);
                    partyMembershipDues.setCreateTime(createTime);
					studentList.add(partyMembershipDues);
		        }
		      }
		      if (!studentList.isEmpty()) {
		        // 开始处理数据
				  if (exportFlag != null && exportFlag == 2) { // 修改
					  // 调用后台的修改方法，具体的方法根据不同的业务来操作
					  for(int i = 0; i < studentList.size() ;i++) {
						  PartyMembershipDues partyMembershipDues1 = studentList.get(i);
						  dfMapper.updateDfinfo(partyMembershipDues1);
					  }
				  } else {
					  // 调用后台的新增方法
					  for(int i = 0; i < studentList.size() ;i++) {
						  PartyMembershipDues partyMembershipDues1 = studentList.get(i);
						  dfMapper.insertDfInfo(partyMembershipDues1);
					  }
				  }

		      }
		      return errorList;
		    } catch (Exception e) {
		      LOGGER.error("importStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
		          this.getClass().getName(),
		          ToStringBuilder.reflectionToString(wb, ToStringStyle.SHORT_PREFIX_STYLE));
		      throw new DBException(QdfRespCode.QDF_020002.getCode(), QdfRespCode.QDF_020002.getMsg(), e);
		    }
	}

}
